import { Divider, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import React, { useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { ActionType, ProColumns } from '@ant-design/pro-table/lib/Table';
import { SorterResult } from 'antd/es/table/interface';
import { IOrganizeTableItem } from '@/pages/data.d';
import { ConnectState } from '@/models/connect';
import { connect, Dispatch } from 'umi';
const RelationModel = React.lazy(() => import('../components/RelationModel'));
import ModalForm from '../components/ModalForm';
import { RoleTableListItem, RoleItem, ProjectListObj } from '../type';

interface UserProps {
  dispatch: Dispatch;
}

const ManagementList: React.FC<UserProps> = (props) => {
  const [queryParams, setQueryParams] = useState<{}>({}); // 表格搜索关键词
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建弹框
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); // 权限管理弹框
  const [stepFormValues, setStepFormValues] = useState({});

  const columns: ProColumns<IOrganizeTableItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      rules: [
        {
          required: true,
          message: '请输入管理员名称',
        },
      ],
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
            }}
          >
            管理员设置
          </a>
          <Divider type="vertical" />
          <a>删除</a>
        </>
      ),
    },
  ];

  const testDataSource = [
    {
      name: '管理者自助',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
    {
      name: '财务指标',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
    {
      name: '教学可视化',
      validity: '2020/08/22',
      invalid: '2020/08/23',
      active: false,
      userId: 'xiaojie',
    },
  ];

  // 新建
  const addManagement = (v: RoleItem) => {
    console.log(v);
    // v.isEnable = 1;
    // v.type = 1;
    // dispatch({
    //   type: 'role/create',
    //   payload: v,
    //   callback: (response: Response) => {
    //     const { header } = response;
    //     handleModalVisible(false);
    //     if (header.code === 200) {
    //       message.success('新建成功');
    //       dispatch({
    //         type: 'userManage/fetchRole',
    //       });
    //     } else {
    //       message.warning('新建失败');
    //     }
    //   },
    // });
  };

  // 获得表格滚动区域高度
  let tabelScroll = 300;
  const wrapperRef = useRef<any>();

  if (wrapperRef && wrapperRef.current) {
    tabelScroll = wrapperRef.current.scrollHeight - 280;
  }

  return (
    <div>
      <ProTable<IOrganizeTableItem>
        actionRef={actionRef}
        scroll={{ y: tabelScroll }}
        rowKey="name"
        options={{
          fullScreen: true,
          reload: false,
          setting: true,
          density: true,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<IOrganizeTableItem>;

          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        dataSource={testDataSource.filter((value) => {
          const keys = Object.keys(queryParams);
          if (keys.length === 0) {
            return true;
          } else {
            for (let i in keys) {
              const key = keys[i];
              if (value[key].toString().indexOf(queryParams[key]) === -1) {
                return false;
              }
            }
          }
          return true;
        })}
        onSubmit={(params) => {
          setQueryParams(params);
        }}
        columns={columns}
      />

      {/* 新建角色弹框 */}
      <ModalForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        title="创建项目"
      >
        <ProTable<RoleTableListItem, RoleItem>
          onSubmit={addManagement}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </ModalForm>

      {/* 权限管理弹框 */}
      {updateModalVisible ? (
        <React.Suspense fallback={null}>
          <RelationModel
            modalVisible={updateModalVisible}
            onCancel={() => {
              handleUpdateModalVisible(false);
            }}
          />
        </React.Suspense>
      ) : (
        ''
      )}
    </div>
  );
};
export default connect(({}: ConnectState) => ({}))(ManagementList);
